"""This script takes a list of dbf files and converts them to CSV in EIA 860 Data """

import os
import arcpy
import csv

def dbf2csv(dbfpath, csvpath):
    ''' To convert .dbf file or any shapefile/featureclass to csv file
        Inputs: 
          dbfpath: full path to .dbf file [input] or featureclass
          csvpath: full path to .csv file [output]  '''
    rows = arcpy.SearchCursor(dbfpath)
    csvFile = csv.writer(open(csvpath, 'wb')) #output csv
    fieldnames = [f.name for f in arcpy.ListFields(dbfpath)]

    allRows = []
    for row in rows:
        rowlist = []
        for field in fieldnames:
            rowlist.append(row.getValue(field))
        allRows.append(rowlist)

    csvFile.writerow(fieldnames)
    for row in allRows:
        csvFile.writerow(row)
    row = None
    rows = None
    
def convert(path):
    """This takes in a path and converts all dbf files in that path to CSV Files """
    for dbf_file in os.listdir(path):
        # Loop through all dbf files
        # and export to dbf
        fileName, fileExt = os.path.splitext(dbf_file)
        if fileExt == '.dbf' or fileExt == '.DBF':
            print dbf_file
            # construct full path to dbf file and csv file
            dbfpath = os.path.join(path, fileName + fileExt)
            csvpath = os.path.join(path, fileName + '.csv')
            dbf2csv(dbfpath, csvpath)
                    
if __name__ == '__main__':
        #2001 - 2001 contain files that need to be converted
        for i in range(2002, 2004):
            path=r'C:/Users/blabarr/Dropbox/1603/Data/EIA/860 Data-Final/eia860%i' %i
            convert(path)